import React from 'react';
import { Avatar, Button } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Conversations } from '@ant-design/x';
import dayjs from 'dayjs';
import '../styles/styles.css';
// import { DEFAULT_CONVERSATIONS_ITEMS } from '../utils/constants';
import type { ConversationItem } from '../types';
import { useNavigate } from 'react-router-dom';

interface ChatSiderProps {
  conversations: ConversationItem[];
  curConversation: string;
  onConversationsChange: (conversations: ConversationItem[]) => void;
  onCurConversationChange: (key: string) => void;
  onMessagesChange: (messages: any[]) => void;
  messageHistory: Record<string, any>;
  loading: boolean;
}

export const ChatSider: React.FC<ChatSiderProps> = ({
  conversations,
  curConversation,
  onConversationsChange,
  onCurConversationChange,
  onMessagesChange,
  messageHistory,
  loading,
}) => {


  const handleAddConversation = () => {
    if (loading) {
      return;
    }

    const now = dayjs().valueOf().toString();
    onConversationsChange([
      {
        key: now,
        label: `New Conversation ${conversations.length + 1}`,
        group: 'Today',
      },
      ...conversations,
    ]);
    onCurConversationChange(now);
    onMessagesChange([]);
  };

  const handleActiveChange = async (val: string) => {
    // The abort execution will trigger an asynchronous requestFallback, which may lead to timing issues.
    // In future versions, the sessionId capability will be added to resolve this problem.
    setTimeout(() => {
      onCurConversationChange(val);
      onMessagesChange(messageHistory?.[val] || []);
    }, 100);
  };

  const handleDeleteConversation = (conversation: ConversationItem) => {
    const newList = conversations.filter((item) => item.key !== conversation.key);
    const newKey = newList?.[0]?.key;
    onConversationsChange(newList);
    // The delete operation modifies curConversation and triggers onActiveChange, so it needs to be executed with a delay to ensure it overrides correctly at the end.
    // This feature will be fixed in a future version.
    setTimeout(() => {
      if (conversation.key === curConversation) {
        onCurConversationChange(newKey);
        onMessagesChange(messageHistory?.[newKey] || []);
      }
    }, 200);
  };

  const navigate = useNavigate();

  const handleBackToWelcome = () => {
    navigate('/');
  };

  return (
    <div className="sider">
      {/* 🌟 Logo */}
      <div className="logo" onClick={handleBackToWelcome} style={{ cursor: 'pointer' }}>
        <img
          src="/img/logo/DanshineAI2.png"
          // src="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*eco6RrQhxbMAAAAAAAAAAAAADgCCAQ/original"
          draggable={false}
          alt="logo"
          width={32}
          height={32}
        />
        <span style={{ fontSize: '18px', fontWeight: 'bold' }} className='logo-text' >Danshine AI Chat X</span>
      </div>

      {/* 🌟 添加会话 */}
      <Button
        onClick={handleAddConversation}
        type="link"
        className="addBtn"
        icon={<PlusOutlined />}
      >
        New Conversation
      </Button>

      {/* 🌟 会话管理 */}
      <Conversations
        items={conversations}
        className="conversations"
        activeKey={curConversation}
        onActiveChange={handleActiveChange}
        groupable
        styles={{ item: { padding: '0 8px' } }}
        menu={(conversation) => ({
          items: [
            {
              label: 'Rename',
              key: 'rename',
              icon: <EditOutlined />,
            },
            {
              label: 'Delete',
              key: 'delete',
              icon: <DeleteOutlined />,
              danger: true,
              onClick: () => handleDeleteConversation(conversation as ConversationItem),
            },
          ],
        })}
      />

      <div className="siderFooter">
        <Avatar size={24} />
        <Button type="text" icon={<QuestionCircleOutlined />} />
      </div>
    </div>
  );
};
